package com.bier.fishproject.utils;


import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Base64;
/**
 * @author base64压缩图片
 */
public class Base64Img {

	private static Base64Img imageUtils;
	
	public static Base64Img getInstance(){
		if(imageUtils==null){
			imageUtils=new Base64Img();
		}
		return imageUtils;
	}
	
	
	/**
	 * 通过base64压缩图片
	 * @param bit
	 * @return
	 */
	public String Bitmap2StrByBase64(Bitmap bit) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bit.compress(CompressFormat.JPEG, 40, bos);// 参数100表示不压缩
		byte[] bytes = bos.toByteArray();
		return Base64.encodeToString(bytes, Base64.DEFAULT);
	}
	
	public byte[] byteImg(Bitmap bit) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bit.compress(CompressFormat.JPEG, 40, bos);// 参数100表示不压缩
		return bos.toByteArray();
	}
	
	
	/**
	 * 根据路径获得图片并压缩，返回bitmap用于显示
	 * @param filePath
	 * @return
	 */
	public Bitmap getSmallBitmap(String filePath) {
	        final BitmapFactory.Options options = new BitmapFactory.Options();
	        options.inJustDecodeBounds = true;
	        BitmapFactory.decodeFile(filePath, options);
		    options.inSampleSize = calculateInSampleSize(options, 800,480);
		    options.inJustDecodeBounds = false;
		    return BitmapFactory.decodeFile(filePath, options);
   }
		
	private int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;
	    if (height > reqHeight || width > reqWidth) {
	             final int heightRatio = Math.round((float) height/ (float) reqHeight);
	             final int widthRatio = Math.round((float) width / (float) reqWidth);
	             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
	    }
	    return inSampleSize;
	}
	
}
